//
//  SLNearlyViewModel.m
//  StarLight
//
//  Created by Duke.wu on 16/5/16.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLNearlyViewModel.h"
#import "SLNetWork.h"
#import "SLNearLyShip.h"
#import "SLNearlyCollectionViewCell.h"



@interface SLNearlyViewModel ()

@property (nonatomic, strong) NSNumber *pageNum;

@property (nonatomic, strong) NSString *location;

@property (nonatomic, strong) NSString *requestPath;

@property (nonatomic, assign) NearlyViewModelType type;

@end

@implementation SLNearlyViewModel

- (instancetype)initWithPage:(NSNumber *)page andType:(NearlyViewModelType)type{
  if (self = [super init]) {
    self.type = type;
    self.pageNum = page;
    [self addObservers];
  }
  return self;
}

- (void)addObservers{
  
  NSDictionary *dic = [DEFAULTS objectForKey:@"loginInformation"];
  
  @weakify(self)
  
  [[RACObserve(self, requestPath) filter:^BOOL(NSString *value) {
    return [value containsString:@"lon="];
  }] subscribeNext:^(NSString *x) {
    
    [SLNetWork getDataWithRequest:x complete:^(id respond, NSError *error) {
      NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
      if (![self.pageNum isEqualToNumber:@1]) {
        [data addObjectsFromArray:self.dataSource];
      }
      
      if (!error) {
        // 船主＝》货Model  货主＝》 shipModel
        if (self.type == NearlyViewModelTypeProduct) {
          NSMutableArray *proList = [SLNearLyProduct mj_objectArrayWithKeyValuesArray:respond[@"data"]];
          [data addObjectsFromArray:proList];
          self.dataSource = data;
        }else{
          
          NSMutableArray *shipList = [SLNearLyShip mj_objectArrayWithKeyValuesArray:respond[@"data"]];
          [data addObjectsFromArray:shipList];
          self.dataSource = data;
        }
      }
    }];
    
  }];
  
  [RACObserve(self, pageNum) subscribeNext:^(NSNumber *page) {
    @strongify(self)
    NSString *request;
    if (self.type == NearlyViewModelTypeProduct) {
      request = [NSString stringWithFormat:@"%@/goods/nearbygoodslist?uid=%@&page=%@&%@",baseUrl,dic[@"id"],page,self.location];
    } else {
      request = [NSString stringWithFormat:@"%@/boat/nearbyboatlist?uid=%@&page=%@&%@",baseUrl,dic[@"id"],page,self.location];
    }

    self.requestPath = request;
  }];
  
  [RACObserve(self, location) subscribeNext:^(NSString *loca) {
    @strongify(self)
    if (![loca isEqualToString:@"lon=0.000000&lat=0.000000"]) {
      self.pageNum = @1;
    }
  }];
  
}


#pragma mark - Public Method


- (void)next{
  self.pageNum = @(self.pageNum.integerValue +1);
}

- (void)first{
  self.pageNum = @1;
}

- (void)changeLocationWithLon:(double)lon lat:(double)lat{
  
  NSString *loc = [NSString stringWithFormat:@"lon=%f&lat=%f",lon,lat];
  self.location = loc;
}


//- (NSMutableArray *)dataSource{
//  if (!_dataSource) {
//    _dataSource = [NSMutableArray arrayWithCapacity:1];
//  }
//  return _dataSource;
//}


@end














